<template>
	<div>
		<view class="bg"></view>
		<view class="container">
			<div v-if="type == 1 && info.pickup.status == 2 && Object.keys(info.pickUpCodes || {}).length">
				<div class="ibox">
					<!-- <canvas canvas-id="myCanvas"
						style="position: absolute; opacity: 1; width: 300px; height: 300px; border: 1px solid; left: -100vw;"></canvas> -->
					<div>入场二维码 / {{ Object.keys(info.pickUpCodes || {}).length }}张</div>
					<swiper circular indicatorDots style="height: 35.5vh;">
						<swiper-item style="margin: 10px 0; text-align: center;"
							v-for="(i, idx) in Object.keys(info.pickUpCodes || {})" :key="i">
							<!-- <div style="font-size: 28rpx;">{{ i }}</div> -->
							<image style="width: 25vh; height: 25vh;" :src="'data:image/png;base64,' + info.pickUpCodes[i]"
								mode="aspectFit" @click="viewPic(info.pickUpCodes[i], i)">
							</image>
							<button
								style="background: #2755CB; color: #fff; font-size: 24rpx; border-radius: 15px; width: 50%; height: 30px; line-height: 30px;"
								@click="shareQrcode(info.pickUpCodes[i], i)">
								分享好友
							</button>
							<div style="height: 40px;"></div>
						</swiper-item>
					</swiper>
				</div>
				<div class="ibox">
					<div class="flexB theme">
						<div>{{ info.tstadiumVenueInfo.stadiumName }}</div>
						<div @click="callpp(info.tstadiumVenueInfo.phone)">
							<uni-icons type="phone-filled" color="#2755CB" size="25"></uni-icons>
						</div>
					</div>
					<div class="flexB f12 c80">
						<div>{{ info.tstadiumVenueInfo.stadiumAddr }}</div>
						<div @click="openMap">
							<uni-icons type="location-filled" color="#4062c5" size="30"></uni-icons>
						</div>
					</div>
				</div>
			</div>
			<div class="ibox">
				<div class="theme mb10">订单信息</div>
				<div class="f12 c80"><span class="t">订单号</span>{{ info.pickup.pickupNo }}</div>
				<div class="f12 c80"><span class="t">下单时间</span>{{ info.pickup.createTime }}</div>
				<div class="f12 c80"><span class="t">订单状态</span><span
						:style="{ color: info.pickup.status == 4 ? 'red' : '#2655CA' }">{{ $utils.orderStatus.find(i => i.value ==
				info.pickup.status).label
						}}</span></div>
				<div class="f12 c80"><span class="t">手机号码</span>{{ info.pickup.phone || '--' }}</div>
				<div class="f12 c80" v-if="info.pickup.pickuoPrice"><span class="t">折扣</span>{{ info.pickup.pickuoPrice || '--'
					}}折</div>
				<div class="f12 c80"><span class="t">合计</span>
					<span v-if="info.pickup.pickuoPrice">
						<span style="color: red;">¥{{ info.pickup.realPay }}</span>
						<span style="text-decoration: line-through; margin-left: 10px;">¥{{ info.pickup.totalPrice }}</span>
					</span>
					<span v-else>
						<span style="color: red;">¥{{ info.pickup.totalPrice }}</span>
					</span>
				</div>
			</div>
			<div v-if="info.tpickupStadiumCard" class="ibox">
				套餐类型：{{ info.tpickupStadiumCard.cardTypeName }}
			</div>
			<div v-else class="ibox">
				<div class="theme mb10">消费明细</div>
				<div v-if="type == 1" class="flexB wrap">
					<div class="ii" v-for="(i, idx) in info.stadiumList" :key="idx">
						<div>{{ i.reserveDate }}</div>
						<div>{{ i.venueName + '/' + i.stadiumTime }}</div>
					</div>
				</div>
				<div v-else class="flexB wrap">
					<div class="ii" v-for="(i, idx) in info.subPickupList" :key="idx">
						<div>{{ i.productName }}</div>
						<div>数量：{{ i.num + ' / 单价：' + i.price }}</div>
					</div>
				</div>
			</div>
			<div class="foot">
				<div class="btn" v-if="info.pickup.status == 1" @click="pay" style="margin-right: 20px;">去支付</div>
				<div class="btn" v-if="info.pickup.status == 1" @click="cancel">取消订单</div>
				<div class="btn" v-if="info.pickup.status == 2 && isWithinOneDay" @click="payReturn">申请退款</div>
			</div>
		</view>
	</div>
</template>

<script>
export default {
	data() {
		return {
			no: '',
			type: 1,
			info: { tstadiumVenueInfo: {}, pickup: {}, stadiumList: [], pickUpCodes: {} },
			list: []
		}
	},
	onLoad(p) {
		this.no = p.no;
		this.type = p.type;
		this.getList();
	},
	onShow() {
		this.no && this.getList()
	},
	computed: {
		isWithinOneDay() {
			// 基准时间
			const baseTime = new Date(this.info.pickup.createTime).getTime();
			// 目标时间的时间戳
			const targetTime = new Date().getTime();
			// 计算时间差（秒），取绝对值
			const timeDiffSeconds = Math.abs(targetTime - baseTime) / 1000;
			// 判断是否≤1天（86400秒）
			return timeDiffSeconds <= 86400;
		},
	},
	methods: {
		async viewPic(url, txt) {
			// let p = await this.generateImageWithText('data:image/png;base64,' + url, txt);
			setTimeout(() => {
				uni.previewImage({
					urls: ['data:image/png;base64,' + url],
				})
			}, 100);
		},
		// 生成带文字的新图片
		async generateImageWithText(imageBase64, text) {
			return new Promise((resolve, reject) => {
				const ctx = uni.createCanvasContext('myCanvas', this);
				const canvasWidth = 300;
				const canvasHeight = 300;

				ctx.setFillStyle('#FFFFFF');
				ctx.fillRect(0, 0, canvasWidth, canvasHeight);

				// 先将 base64 转为临时路径
				this.base64ToTempFilePath(imageBase64, (tempImagePath) => {
					if (!tempImagePath) {
						reject(new Error('无法生成临时图片路径'));
						return;
					}

					// 现在可以安全地使用 drawImage 了
					ctx.drawImage(tempImagePath, 20, 20, canvasWidth - 40, canvasHeight - 40);

					ctx.setFontSize(18);
					ctx.setFillStyle('#000000');
					const textWidth = ctx.measureText(text).width;
					const textX = (canvasWidth - textWidth) / 2;
					const textY = 25;
					ctx.fillText(text, textX, textY);

					ctx.draw(false, () => {
						// 导出 canvas 为临时图片路径
						uni.canvasToTempFilePath({
							canvasId: 'myCanvas',
							success: (res) => {
								resolve(res.tempFilePath);
							},
							fail: (err) => {
								console.error('canvas 导出临时路径失败：', err);
								reject(err);
							}
						}, this);
					});
				});
			});
		},
		// 如果你确实需要将生成的临时图片路径再转为 base64，可以使用如下方法
		tempFilePathToBase64(tempFilePath) {
			return new Promise((resolve, reject) => {
				// #ifdef APP-PLUS || MP
				const fs = uni.getFileSystemManager();
				fs.readFile({
					filePath: tempFilePath,
					encoding: 'base64',
					success: (res) => {
						const base64 = 'data:image/png;base64,' + res.data;
						resolve(base64);
					},
					fail: reject
				});
				// #endif

				// #ifdef H5
				// H5 可以通过 new Image() 和 canvas 来转换，略复杂，此处略
				reject(new Error('H5 暂未实现'));
				// #endif
			});
		},
		// 分享二维码入口
		shareQrcode(code, txt) {
			if (!code) {
				uni.showToast({ title: '二维码数据为空', icon: 'none' });
				return;
			}

			// 第一步：将base64转换为本地临时路径
			this.base64ToTempPath(code, txt, (tempPath) => {
				if (tempPath) {
					// 第二步：调用微信分享接口
					this.shareToWechat(tempPath);
				} else {
					uni.showToast({ title: '图片转换失败', icon: 'none' });
				}
			});
		},

		// 将base64字符串转换为本地临时文件路径
		async base64ToTempPath(base64Data, txt, callback) {
			// 去掉base64前缀（如"data:image/png;base64,"）
			// uni.showLoading({ title: '加载中...', mask: true });
			// let p = await this.generateImageWithText('data:image/png;base64,' + base64Data, txt);

			// let f = await this.tempFilePathToBase64(p);
			const base64 = base64Data.replace(/^data:image\/\w+;base64,/, "");
			// 生成临时文件路径（微信小程序专用路径）
			const timestamp = new Date().getTime();
			const tempFilePath = wx.env.USER_DATA_PATH + `/qrcode_${timestamp}.png`;
			// uni.hideLoading();
			// 写入文件
			uni.getFileSystemManager().writeFile({
				filePath: tempFilePath,
				data: base64,
				encoding: 'base64',
				success: () => {
					callback(tempFilePath); // 转换成功，返回临时路径
				},
				fail: (err) => {
					console.error('base64转换失败：', err);
					callback(null);
				}
			});
		},

		// 调用微信接口分享图片
		shareToWechat(imagePath) {
			// 微信小程序分享图片接口
			wx.showShareImageMenu({
				path: imagePath, // 本地临时图片路径
				success: () => {
					uni.showToast({ title: '分享成功', icon: 'success' });
					this.$refs.cc.close(); // 分享后关闭弹窗
				},
				fail: (err) => {
					console.log('分享取消或失败：', err);
					// 用户取消分享也会进入fail，这里可以不提示
				}
			});
		},
		pay() {
			if (this.type == 1) {
				uni.navigateTo({
					url: `/pages/prePay?isOrder=1&no=${this.info.pickup.pickupNo}`
				});
			} else {
				let arr = this.info.subPickupList;
				uni.setStorageSync('carArr', arr);
				uni.navigateTo({
					url: `/pages/order?isOrder=1`
				});
			}
		},
		cancel() {
			uni.showModal({
				title: '提示',
				content: '确定取消订单？',
				success: (res) => {
					if (res.confirm) {
						uni.showModal({
							title: '提示',
							content: '请订阅订单取消状态，才能取消',
							success: (res) => {
								if (res.confirm) {
									// 用户确认后，再次通过按钮触发订阅
									uni.requestSubscribeMessage({
										tmplIds: ['od-dStXxYIuS5ESGo1JjURI9DySit2UwjBZAL56y_rk'],
										success: (res) => {
											if (res['od-dStXxYIuS5ESGo1JjURI9DySit2UwjBZAL56y_rk'] == 'accept') {
												this.$request({
													url: '/order/cancelOrder/' + this.info.pickup.id,
													method: 'get',
												}).then(res => {
													this.$msg('操作成功');
													setTimeout(() => uni.navigateBack(), 500)
												})
											} else {
												this.$msg('取消订阅，无法取消');
											}
										},
									})
								}
							}
						});
					} else if (res.cancel) {
					}
				}
			});
		},
		payReturn() {
			uni.showModal({
				title: '提示',
				content: '确定申请退款？',
				success: (res) => {
					if (res.confirm) {
						uni.showModal({
							title: '提示',
							content: '请订阅订单退款状态，才能退款',
							success: (res) => {
								if (res.confirm) {
									// 用户确认后，再次通过按钮触发订阅
									uni.requestSubscribeMessage({
										tmplIds: ['fZ67f0WiurAPyJluvb4HZTPXW52R6gbAsbAtIq-FBKY'],
										success: (res) => {
											if (res['fZ67f0WiurAPyJluvb4HZTPXW52R6gbAsbAtIq-FBKY'] == 'accept') {
												this.$request({
													url: '/wxpay/refundOrderV3',
													data: {
														orderNo: this.no
													}
												}).then(res => {
													this.$msg('管理员审核通过后将退款成功');
													setTimeout(() => uni.navigateBack(), 500)
												})
											} else {
												this.$msg('取消订阅，无法退款');
											}
										}
									})
								}
							}
						});
					} else if (res.cancel) {
					}
				}
			});

		},
		openMap() {
			uni.openLocation({
				name: this.info.tstadiumVenueInfo.stadiumAddr || '',
				latitude: this.info.tstadiumVenueInfo.latitude * 1,
				longitude: this.info.tstadiumVenueInfo.longitude * 1,
				success: function () {
					console.log('success');
				},
				fail: (err) => {
					console.log(err);
					this.$msg('经纬度无效')
				}
			});
		},
		callpp(v) {
			if (!v) return this.$msg('手机号无效')
			uni.makePhoneCall({
				phoneNumber: v,
			});
		},
		getList() {
			this.$request({
				url: '/orderList/orderDetail',
				method: 'get',
				data: {
					pickupNo: this.no,
				},
			}).then(res => {
				this.info = res.data;
			})
		}

	}
}
</script>

<style lang="scss">
.t {
	display: inline-block;
	width: 100px;
}

.bg {
	width: 100%;
	position: absolute;
	top: 0;
	height: 20vh;
	background: $theme;
	border-radius: 0 0 20px 20px;
	z-index: -1;
}

.foot {
	display: flex;
	justify-content: center;
}

.btn {
	text-align: center;
	width: 100px;
	height: 40px;
	line-height: 40px;
	border-radius: 20px;
	background: $theme;
	color: #fff;
}

.ii {
	width: 48%;
	margin: 0 auto;
	background: $theme;
	padding: 10rpx 20rpx;
	border-radius: 10rpx;
	color: #fff;
	font-size: 24rpx;
	margin-bottom: 10px;
}
</style>